package com.jiajia.study.nio.chapter02;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Set;

public class NioServer05 {
    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.bind(new InetSocketAddress(8888));

        Selector selector = Selector.open();
        SelectionKey selectionKey = serverSocketChannel.register(selector, 0, null);
        selectionKey.interestOps(SelectionKey.OP_ACCEPT);

        while (true) {
            selector.select();
            Set<SelectionKey> selectionKeys = selector.selectedKeys();

            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            if(iterator.hasNext()) {
                SelectionKey selectionKeyItem = iterator.next();
                iterator.remove();

                if(selectionKeyItem.isAcceptable()) {
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    socketChannel.configureBlocking(false);
                    StringBuilder stringBuilder = new StringBuilder();
                    // 往客户端写数据
                    for (int i = 0; i < 10000000; i++) {
                        stringBuilder.append("s");
                    }
                    String data = stringBuilder.toString();
                    ByteBuffer byteBuffer = StandardCharsets.UTF_8.encode(data);
                    // 写数据
                    while (byteBuffer.hasRemaining()) {
                        int write = socketChannel.write(byteBuffer);
                        System.out.println("write length : " + write);
                    }
                }
            }
        }


    }
}
